import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_uploader/flutter_uploader.dart';
import '../model/ftpfile.dart';
import '../../model/space_item.dart';
import '../helper/uidata.dart';
import 'package:path/path.dart';
import 'package:uuid/uuid.dart';

import '../model/upfile.dart';
import 'Helper.dart';

class UploadHelper {
  static final uploader = FlutterUploader();
  //static final url = "http://47.95.205.213:12345/upload";
  static final url = "http://47.108.62.6:12346/upload2";
  //static final url =UIData.fileUploadServer;
  static var uuid = Uuid();
  static UpFileProvider xx = UpFileProvider();
  static bool IfInit = false;
  static bool IfInit2 = false;

  static FileItem getItem(String path) {
    return FileItem(
        // filename: basename(path), savedDir: dirname(path), fieldname: "file");
        path: path);
  }

  static Future<String> UpLoad(
      String path, String tag1, String guid, String spaceId,
      {int fType = 0}) async {
    var fileItem = UploadHelper.getItem(path);

    // var taskId = await UploadHelper.uploader.enqueue(
    //     url: UploadHelper.url,
    //     files: [fileItem],
    //     method: UploadMethod.POST, // HTTP method  (POST or PUT or PATCH)
    //     //headers: {"apikey": "api_123456", "userkey": "userkey_123456"},
    //     data: {"guid": guid}, // any data you want to send in upload request
    //     showNotification:
    //         true, // send local notification (android only) for upload status
    //     tag: fileItem.filename);
    var filename = basename(path);
    var savedDir = dirname(path);
    var taskId = await UploadHelper.uploader
        .enqueue(getUpload(guid, UploadHelper.url, filename, fileItem));
    var a = new UpFile(
        guid, spaceId, tag1, filename, savedDir, path, taskId, 0, 0, fType);
    if (xx.db == null) await xx.create();

    await xx.insert(a);
    return taskId;
  }

  static MultipartFormDataUpload getUpload(
      String guid, url, tag, FileItem file) {
    // return RawUpload(
    //   url:url,
    //   method: UploadMethod.POST,
    //   headers: [],
    //   allowCellular:true,
    //   path:path,
    //   tag:"",
    // );

    return MultipartFormDataUpload(
      url: url,
      data: {"guid": guid},
      files: [file],
      method: UploadMethod.POST,
      tag: tag,
      headers: {"auth": UIData.token},
      allowCellular: true,
    );
  }

  static Future<UpFile?> UpLoad11(
      File file, String tag1, String guid, String spaceId) async {
    var pb1 = file.existsSync();
    if (pb1 == false) {
      SnackBar(
        content: Text("文件不存在！"),
      );
      print("文件不存在！");
      return null;
    }

    var fileItem = UploadHelper.getItem(file.absolute.path);
    var path = file.absolute.path;

    var guid = Helper.GetGuid();
    var size1 = file.lengthSync();
    var x1 = SpaceItem(0, guid, UIData.CurrentUser!.Guid, spaceId, 0, file.path,
        Helper.DateTimeNowString(), -1, size1, "", "", "", "", "", tag1);
    var pbx = await SpaceItem.Add(x1);
    if (!pbx) return null;

    // var taskId = await UploadHelper.uploader.enqueue(
    //     url: UploadHelper.url,
    //     files: [fileItem],
    //     method: UploadMethod.POST, // HTTP method  (POST or PUT or PATCH)
    //     //headers: {"apikey": "api_123456", "userkey": "userkey_123456"},
    //     data: {"guid": guid}, // any data you want to send in upload request
    //     showNotification:
    //         true, // send local notification (android only) for upload status
    //     tag: fileItem.filename);

    var filename = basename(path);
    var savedDir = dirname(path);
    var taskId = await UploadHelper.uploader
        .enqueue(getUpload(guid, UploadHelper.url, filename, fileItem));
    var a =
        UpFile(guid, spaceId, tag1, filename, savedDir, path, taskId, 0, 0, 0);

    // var a = new UpFile(guid, spaceId, tag1, fileItem.filename,
    //     fileItem.savedDir, file.absolute.path, taskId, 0, 0, 0);

    if (xx.db == null) await xx.create();
    await xx.insert(a);
    return a;
  }

  static Future<String> UpLoad2(
      int fType, String path, String tag1, String guid, String spaceId) async {
    var fileItem = UploadHelper.getItem(path);

    // var taskId = await UploadHelper.uploader.enqueue(
    //     url: UIData.imageUploadServer,
    //     files: [fileItem],
    //     method: UploadMethod.POST,
    //     headers: {"auth": UIData.token},
    //     data: {"guid": guid}, // any data you want to send in upload request
    //     showNotification:
    //         true, // send local notification (android only) for upload status
    //     tag: tag1);
    var filename = basename(path);
    var savedDir = dirname(path);

    var taskId = await UploadHelper.uploader
        .enqueue(getUpload(guid, UploadHelper.url, filename, fileItem));
    var a = new UpFile(
        guid, spaceId, tag1, filename, savedDir, path, taskId, 0, 0, fType);

    if (xx.db == null) await xx.create();

    await xx.insert(a);

    return taskId;
  }

  static Future<List<UpFile>> getList() async {
    if (xx.db == null) await xx.create();
    return xx.getList() as List<UpFile>;
  }

  static Future<List<UpFile>> getListBySpaceID(String sID) async {
    if (xx.db == null) await xx.create();
    var yy = await xx.getList();
    return yy?.where((p) => p.spaceId == sID) as List<UpFile>;
  }

  static Future<UpFile> getByTaskId(String taskId) async {
    if (xx.db == null) await xx.create();
    return xx.getByTaskId(taskId) as UpFile;
  }

  static Future<UpFile> getByGuid(String guid) async {
    if (xx.db == null) await xx.create();
    return xx.getOne(guid) as UpFile;
  }

  static void uploadCompleted() {
    if (IfInit == true) return;
    IfInit = true;
    uploader.result.listen((result) async {
      if (xx.db == null) await xx.create();
      var a = await xx.getByTaskId(result.taskId);

      if (a != null) {
        a.done = 100;
        await xx.update(a);
        //print('11111111111111');
        print(a.toJson());
        if (a.fType >= 0) {
          var b = await SpaceItem.Get(a.guid);
          b!.State = 0;
          b.FileName = a.baseName;
          SpaceItem.Update(b);
        } else {
          var b = await FtpFile.Get(a.guid);
          b!.State = 0;
          b.FileName = a.baseName;
          FtpFile.Update(b);
        }
      }
    }, onError: (ex, stacktrace) {
      print("错误:" + ex.toString());
    });
  }
}
